<?php
/**
 * Created by PhpStorm.
 * Author: 黑瞎子
 * Date: 2018/4/4
 * Time: 13:11
 */

namespace app\api\service;


use app\api\model\ThirdApp as ThirdAppModel;
use app\lib\exception\TokenException;
use think\Cache;

class AppToken extends Token
{
    //验证用户，用户存在则生成token令牌，把用户信息存入缓存。返回token
    public function get($ac, $sc){
        $app = ThirdAppModel::check($ac, $sc);
        if (!$app){
            throw new TokenException([
                'msg' => '授权失败',
                'errorCode' => 10004
            ]);
        }else{
            $scope = $app->scope;
            $uid = $app->id;
            $values = [
                'scope' => $scope,
                'id' => $uid
            ];
            $token = $this->saveToCache($values);
            return $token;
        }
    }

    //用户信息保存到缓存
    private function saveToCache($values){
        $token = self::generateToken();
        $expire_in = config('setting.token_expire_in');
        $result = Cache::set($token, $values, $expire_in);
        if (!$result){
            throw new TokenException([
                'msg' => '服务器缓存异常',
                'errorCode' => 10005,
            ]);
        }
        return $token;
    }
}